package hey.dylan.service.impl;

import hey.dylan.mapper.MenuMapper;
import hey.dylan.model.LoginUser;
import hey.dylan.model.Menu;
import hey.dylan.model.MenuReObj;
import hey.dylan.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<MenuReObj> getMenuInfoById() {
        LoginUser loginUser = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<Menu> menuList = menuMapper.selectAllByUserId(loginUser.getUser().getId());
        return doFormat(menuList);
    }

    private List<MenuReObj> doFormat(List<Menu> menuList) {
        List<MenuReObj> rtnList = new ArrayList<>();
        for(Menu menu01 : menuList){
            String id01 = String.valueOf(menu01.getId());
            if(id01.length()==1) {
                MenuReObj fm = new MenuReObj();
                fm.setMenuName(menu01.getMenuName());
                fm.setPath(menu01.getPath());
                fm.setComponent(menu01.getComponent());
                fm.setIcon(menu01.getIcon());
                for (Menu menu02 : menuList) {
                    String id02 = String.valueOf(menu02.getId());
                    if (id02.length() != 1 && id02.startsWith(id01)) {
                        MenuReObj sm = new MenuReObj();
                        sm.setMenuName(menu02.getMenuName());
                        sm.setPath(menu02.getPath());
                        sm.setComponent(menu02.getComponent());
                        sm.setIcon(menu02.getIcon());
                        fm.getChildren().add(sm);
                    }
                }
                rtnList.add(fm);
            }
        }
        return rtnList;
    }
}
